package org.eae.eldf.service.sys.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.eae.eldf.dao.sys.ISysOperatorDao;
import org.eae.eldf.dao.sys.ISysRoleDao;
import org.eae.eldf.dao.sys.ISysRolePurviewDao;
import org.eae.eldf.dao.sys.impl.SysRoleDaoImpl;
import org.eae.eldf.dto.sys.SysRoleQueryDto;
import org.eae.eldf.entity.sys.SysOperatorRole;
import org.eae.eldf.entity.sys.SysPurview;
import org.eae.eldf.entity.sys.SysRole;
import org.eae.eldf.entity.sys.SysRolePurview;
import org.eae.eldf.framework.exception.ServiceException;
import org.eae.eldf.framework.pager.Pagination;
import org.eae.eldf.framework.persistence.Criteria;
import org.eae.eldf.framework.service.BaseServiceImpl;
import org.eae.eldf.framework.spring.SpringSecurityUtils;
import org.eae.eldf.service.sys.SysRoleService;

@Service
@Transactional
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements
		SysRoleService {

	 private ISysOperatorDao sysOperatorDao;
	 @Autowired
	public void setSysOperatorDao(ISysOperatorDao sysOperatorDao) {
		this.sysOperatorDao = sysOperatorDao;
	}

	 private ISysRolePurviewDao rolePurviewDao;
	 
	 @Autowired
	public void setRolePurviewDao(ISysRolePurviewDao rolePurviewDao) {
		this.rolePurviewDao = rolePurviewDao;
	}

	private ISysRoleDao roleDao;
    @Autowired
	public void setRoleDao(SysRoleDaoImpl roleDao) {
		this.roleDao = roleDao;
		this.dao = roleDao;
	}


	@Override
	public Pagination<SysRole> pageRoleList(Pagination<SysRole> pager,
			SysRoleQueryDto searchDto) {
		pager=roleDao.pageRoleList(pager, searchDto);
		return pager;
	}

	@Override
	public void delete(Long id) {
		//先删除角色的权限
		roleDao.delete(Criteria.create(SysRolePurview.class).where("sysPurviewId", new Object[]{id}));
		//删除用户对应的角色
		sysOperatorDao.delete(Criteria.create(SysOperatorRole.class).where("sysRoleId", new Object[]{id}));
		Criteria criteria=Criteria.create(SysRole.class).where("sysRoleId", new Object[]{id});
		roleDao.delete(criteria);
	}

	@Override
	public SysRole findById(Long id) {
		return roleDao.get(SysRole.class, id);
	}

	

	@Override
	public List<SysPurview> queryPurviewByRole(Long roleid) {
		return roleDao.queryPurviewByRole(roleid);
	}

	@Override
	public void saveRolePurview(Long roleId, List<Long> purid) {
		//先删除角色对应的权限 sys_role_purview
		rolePurviewDao.delete(Criteria.create(SysRolePurview.class).where("sysRoleId", new Object[]{roleId}));
		if(null!=purid){
			for(Long pid:purid){
				SysRolePurview rp = new SysRolePurview();
				rp.setDcreatetime(new Date());
				rp.setDlastupdatetime(new Date());
				rp.setSlastupdateuser(SpringSecurityUtils.getCurrentUserName());
				rp.setSysPurviewId(pid);
				rp.setSysRoleId(roleId);
				rolePurviewDao.insert(rp);
			}
		}
		
		
	}

}
